package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"userServer/config"
	"userServer/model"
)

type RegisterRequest struct {
	Username string `json:"username" binding:"required"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required"`
}

func Register(c *gin.Context) {
	var req RegisterRequest

	// 1. 绑定请求体并验证参数
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	// 2. 查重用户名
	var count int64
	config.DB.Model(&model.User{}).Where("username = ?", req.Username).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
		return
	}

	// 3. 查重邮箱
	config.DB.Model(&model.User{}).Where("email = ?", req.Email).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱已存在"})
		return
	}

	// 4. 创建用户
	user := model.User{
		Username: req.Username,
		Email:    req.Email,
		Password: req.Password, // 建议后续加密哈希
	}
	if err := config.DB.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败"})
		return
	}

	// 5. 注册成功返回
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "注册成功",
	})
}
